import concurrent.futures
import os
from os.path import exists
import openpyxl
import logging
import threading

logging.basicConfig(filename='running log.txt', level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

wb = openpyxl.Workbook()
ws = wb.active
ws.title = "Data"

data_type_1 = ['产品编号', '检测日期', '检测时间', '最大值', '最小值/对应角度', '平均值', '测试结果']

# Excel 中的第一行：列名
def title_1():
    column_names = data_type_1
    for col_idx, col_name in enumerate(column_names, start=1):
        ws.cell(row=1, column=col_idx, value=col_name)
        # ws_2.cell(row=1, column=col_idx, value=col_name)
    logging.info('Write down the title')

# 读取 txt 文件
def read_txt_file(file_path):
    try:
        with open(file_path, 'r') as f:
            return f.readlines()
    except FileNotFoundError:
        logging.error(f"File not found: {file_path}")
        return None

# 读取单个 TXT 的数据
def read_TPS1_data(file_path):
    lines = read_txt_file(file_path)
    logging.info('Running read_Tps_data')
    logging.info(f'file name is : {file_path}')
    valid_data = []
    if lines is not None:
        for line in range(1, len(lines)):
            logging.info(f'read line: {line}')
            if lines:
                data = lines[line].split()
                logging.info(f'Reading data : {data}')
                has_number = any(char.isdigit() for char in data[0])
                if has_number:
                    product_No = (data[0])
                    check_date = (data[1])
                    check_time = (data[2])
                    up_value = float(data[3])
                    low_value = float(data[4])
                    average_value = float(data[5])
                    logging.info(f'product_No, check_date, check_time, up_value, low_value, average_value are : {product_No, check_date, check_time, up_value, low_value, average_value}')

                    try:
                        if len(data)>6:
                            test_result = data[6]
                            valid_data.append(
                                [product_No, check_date, check_time, up_value, low_value, average_value, test_result])  # 写入内存中的 Excel

                        else:
                            valid_data.append(
                                [product_No, check_date, check_time, up_value, low_value, average_value])  # 写入内存中的 Excel
                    except Exception as e:
                        logging.error(f"Error reading file: {e}")
                        continue

                else:
                    logging.warning(f"Invalid data format in line {line}: {data}")
                    # print(f"在文件 {file_path} 的第 {line} 行，产品编号为： {data[0]}，数据无效，无法读取。")

    else:
        logging.error(f"Could not read file: {file_path}")

    return valid_data

def process_file(file_name):
    file_path = os.path.join(r'M4REK', file_name)
    data = read_TPS1_data(file_path)
    for row_data in data:
        ws.append(row_data)

def get_file_names(directory):
    return [f for f in os.listdir(directory) if f.endswith('.txt')]



def FormatXmlExcelThread(file_path):
    try:
        workbook = openpyxl.load_workbook(file_path)
        sheet = workbook.active
        yellow_fill = openpyxl.styles.PatternFill(start_color='FFFF00', end_color='FFFF00', fill_type='solid')
        red_font = openpyxl.styles.Font(color='FF0000')
        default_font = openpyxl.styles.Font(color='000000')
        logging.info(f'开始在Excel文件中寻找NG的数据：{file_path}')
        for row in sheet.iter_rows():
            for cell in row:
                if str(cell.value) == 'NG' :
                    cell.fill = yellow_fill
                    cell.font = red_font
                else:
                    cell.font = default_font
        workbook.save(file_path)
    except Exception as e:
        logging.error(f"Error formatting XML file: {e}")


def main():
    title_1()
    folder_path = r'M4REK'
    all_data = []
    logging.info(f'There are {len(get_file_names(folder_path))} files in the folder.')
    file_names = get_file_names(folder_path)
    threads = []
    for file_name in file_names:
        t = threading.Thread(target=process_file, args=(file_name,))
        threads.append(t)
        t.start()

    for t in threads:
        t.join()

    wb.save('CalibrationReportData.xlsx')
    FormatXmlExcelThread('CalibrationReportData.xlsx')  # 查找NG 数据
    print('Done')

if __name__ == '__main__':
    main()
